import { login, logout, getUserInfo, register } from '@/api/user'
import { getMenuRouter } from '@/api/menu'
import { getToken, removeToken } from '@/utils/auth'
import { utils } from '@/utils/utils';
import { resetRouter, constantRoutes } from '@/router'
import analysisRouterParam from '@/utils/analysis-router-param.js'

const getDefaultState = () => {
  return {
    token: getToken(),
    realIp: returnCitySN["cip"],
    name: '',
    avatar: '',
    nodeInfo: {},
    userInfo: {},
    routers: [],
    addRouters: [],
    routerRules: [],
    routerMenu: [],
    newOrderArr: [],
    newUserArr: [],
    reserveNewOrderArr:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_NODEINFO: (state, nodeInfo) => {
    state.nodeInfo = nodeInfo
  },
  setRouters: (state, routers) => {
    state.addRouters = routers;
  },
  setLeftRouters: (state, routers) => {
    let rout = JSON.parse(JSON.stringify(constantRoutes));
    state.routers = rout.concat(routers);
  },
  setRouterRules: (state, routers) => {
    state.routerRules = routers;
  },
  setRouterMenu: (state, routers) => {
    state.routerMenu = routers;
  },
  setNewOrderAmount: (state, obj) => {
    state.newOrderArr.push(obj);
  },
  delNewOrderAmount: (state, obj) => {
    var order = state.newOrderArr.filter((item) => {
      if (item.order_id != obj.order_id) {
        return item;
      }
    });
    state.newOrderArr = order;
  },
  setNewUserAmount: (state, obj) => {
    state.newUserArr.push(obj);
  },
  delNewUserAmount: (state, obj) => {
    var order = state.newUserArr.filter((item) => {
      if (item.uid != obj.uid) {
        return item;
      }
    });
    state.newUserArr = order;
  },
  setReserveNewOrderAmount: (state, obj) => {
    state.reserveNewOrderArr.push(obj);
  },
  delReserveNewOrderAmount: (state, obj) => {
    var order = state.reserveNewOrderArr.filter((item) => {
      if (item.reserve_id != obj.reserve_id) {
        return item;
      }
    });
    state.reserveNewOrderArr = order;
  },

  
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const {
      username,
      password,
      verifyCode
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        verifyCode: verifyCode
      }).then(response => {
        const { data } = response
        if (data.appstr) {
          utils.cacheSet('userappstr', data.appstr);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },


  register({ commit }, userInfo) {
    const {
      username,
      password,
      verifyCode,
      phoneCode,
      nickname,
      referee,
    } = userInfo;

    return new Promise((resolve, reject) => {
      register({
        username: username.trim(),
        password: password,
        verifyCode: verifyCode,
        phoneCode: phoneCode,
        nickname: nickname,
        referee: referee ? referee : 'admin',
      }).then(response => {
        const { data } = response
        if (data.appstr) {
          utils.cacheSet('userappstr', data.appstr);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },


  /**
   * 左边数据列表
   * @param {*} param0 
   */
  getMenuRouter({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMenuRouter().then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        let tree = data.tree;//buildTree(data.list,'0','id','pid');

        let asyncLeftRouters = filterAsyncLeftRouter(tree);






        let asyncRouters = filterAsyncRouter(data.list);

        commit("setRouters", asyncRouters);
        commit("setLeftRouters", asyncLeftRouters);
        commit("setRouterMenu", data.list);
        commit("setRouterRules", asynsRules(data.list));

        resolve(data)

      }).catch(error => {
        console.log('error', error)
        reject(error)
      })
    })

  },


  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { nickname, avatar, avatar_text } = data.user
       

        commit('SET_NAME', (nickname ? nickname : data.user.username))
        commit('setUserInfo', data.user)
        commit('SET_AVATAR', avatar_text ? avatar_text : require('@/assets/avatar.jpeg'))
        resolve(data)
      }).catch(error => {
        console.log('error', error)
        reject(error)
      })
    })
  },



  setNewOrderCount({ commit, state }, context) {
    commit('setNewOrderAmount', context);
  },

  delNewOrderCount({ commit, state }, context) {
    commit('delNewOrderAmount', context);
  },

  setNewUserCount({ commit, state }, context) {
    commit('setNewUserAmount', context);
  },

  delNewUserCount({ commit, state }, context) {
    commit('delNewUserAmount', context);
  },

  setReserveNewOrderCount({ commit, state }, context) {
    commit('setReserveNewOrderAmount', context);
  },

  delReserveNewUserCount({ commit, state }, context) {
    commit('delReserveNewOrderAmount', context);
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        utils.cacheRemove('userappstr');
        // removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      utils.cacheRemove('userappstr');
      // removeToken() // must remove  token  first
      // commit('RESET_STATE')
      resolve()
    })
  },


  setNodeinfo({
    commit
  }, data) {
    return new Promise(resolve => {
      commit('SET_NODEINFO', data)
      resolve()
    })
  }
}

/**
 * 权限数组
 * @param {*} routers 
 */
function asynsRules(routers) {
  let rules = [];
  routers.map((item) => {
    if (item.name) {
      rules.push({ id: item.id, name: item.name });
    }

    return true;
  });

  return rules;
}

/**
 * 动态路由数组
 * @param {*} routers 
 * @param {*} type 
 */
function filterAsyncRouter(routers) {
  let list = [
    {
      path: '/',
      name: 'Layouts',
      component: () => import('@/layout'),
      children: []
    }
  ];

  let rules = [];
  let tpls = [];
  routers.map((router) => {



    if (router.tpl && router.name) {
      var routerUrl = analysisRouterParam.init(router.name, {});
      // console.log(routerUrl,router.name)
      var obj = {
        hidden: router.ismenu ? false : true,
        path: routerUrl.path,
        query: routerUrl.query,
        name: router.id + '',
        meta: {
          title: router.title,
          icon: router.icon,
          affix: true
        },

        component: loadView(router.tpl)
      };
      // console.log(router.tpl,router.id)

      rules.push(obj);

    }
    return true;
  });

  rules.push({ path: '*', redirect: '/404', hidden: true });
  list[0].children = rules;
  // console.log(list);
  return list;
}



/**
 * 左边菜单数组
 * @param {*} routers 
 */
function filterAsyncLeftRouter(routers, type = false) {

  let accessedRouters = routers.filter(router => {
    router.hidden = router.ismenu ? false : true;
    router.path = router.name;
    router.name = router.id + '';

    if (router.tpl) {

      router.meta = {
        title: router.title,
        icon: router.icon,
        affix: true
      }

      router.component = loadView(router.tpl);

    } else {

      router.component = () => import('@/layout');
      router.redirect = 'noRedirect';
      router.meta = {
        title: router.title,
        icon: router.icon,
        requireAuth: true
      }
    }

    //存在子集
    if (router.children && router.children.length) {
      router.children = filterAsyncLeftRouter(router.children);
    }

    return true;
  });

  return accessedRouters;
}

function loadView(view) {
  return resolve => require(["@/views/" + view + ""], resolve);
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
